package everyday;

/**
 * @Author: Siantar
 * @Date: 2023-06-18-21:30
 * @Description: 1.0
 */
public class T1254 {

    public int closedIsland(int[][] grid) {
        int n = grid.length;
        int m = grid[0].length;
        int sum = 0;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if (grid[i][j] == 0 && dfs(n, m, grid, i, j)) {
                    sum++;
                }
            }
        }
        return sum;
    }

    public boolean dfs(int n, int m, int[][] grid, int x, int y) {
        if (x < 0 || x >= n || y < 0 || y >= m) {
            return false;
        }
        if (grid[x][y] == 1) {
            return true;
        }
        grid[x][y]=1;
        return dfs(n, m, grid, x + 1, y) && dfs(n, m, grid, x - 1, y) && dfs(n, m, grid, x, y + 1) && dfs(n, m, grid, x, y - 1);
    }
}
